package com.getpebble.android.jskit.webapps;

import android.content.Context;
import android.os.Bundle;
import android.webkit.WebView;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.jskit.concurrency.SyncStepRunnable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;

public class NoUiWebappBase implements WebappRunHost {
    protected String mAppInfoJsonUrl = "";
    protected WeakReference<Context> mBackingContextRef = null;
    public final UUID mClientUuid = UUID.randomUUID();
    protected String mLastUrlStringLoaded = null;
    protected WebappSupport mPrivateWebAppSupportObject = null;
    public String mQueuedLoadUrl = null;
    protected Lock queuedUrlResourceLock = new ReentrantLock();

    public String lastUrlStringLoaded() {
        return this.mLastUrlStringLoaded;
    }

    public UUID clientUuid() {
        return this.mClientUuid;
    }

    public String clientUuidAsString() {
        return clientUuid().toString();
    }

    public String getQueuedLoadUrlWithAtomicClear() {
        this.queuedUrlResourceLock.lock();
        String rv = this.mQueuedLoadUrl;
        this.mQueuedLoadUrl = null;
        this.queuedUrlResourceLock.unlock();
        return rv;
    }

    public void newAppInfoJsonUrl(String urlString) {
        if (urlString == null) {
            urlString = "";
        }
        this.mAppInfoJsonUrl = urlString;
    }

    public String getAppInfoUrlString() {
        return this.mAppInfoJsonUrl;
    }

    public JSONObject loadAppInfoJson() {
        Exception e;
        Throwable th;
        File f = null;
        try {
            f = new File(new URL(getAppInfoUrlString()).toURI());
        } catch (Exception e2) {
            Trace.debug("NoUiWebappBase", "loadAppInfoJson", e2);
        }
        if (f == null) {
            return null;
        }
        String allOfTheJsonText = null;
        InputStream inputStream = null;
        try {
            Writer writer = new StringWriter();
            InputStream inputStream2 = new FileInputStream(f);
            try {
                IOUtils.copy(inputStream2, writer, "UTF-8");
                allOfTheJsonText = writer.toString();
                if (inputStream2 != null) {
                    try {
                        inputStream2.close();
                        inputStream = inputStream2;
                    } catch (IOException e3) {
                        Trace.debug("NoUiWebappBase", "loadAppInfoJson: error closing stream", e3);
                        inputStream = inputStream2;
                    }
                }
            } catch (Exception e4) {
                e2 = e4;
                inputStream = inputStream2;
                try {
                    Trace.debug("NoUiWebappBase", "loadAppInfoJson", e2);
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e32) {
                            Trace.debug("NoUiWebappBase", "loadAppInfoJson: error closing stream", e32);
                        }
                    }
                    if (allOfTheJsonText == null) {
                        try {
                            return new JSONObject(allOfTheJsonText);
                        } catch (Exception e22) {
                            Trace.debug("NoUiWebappBase", "loadAppInfoJson", e22);
                            return null;
                        }
                    }
                    Trace.debug("NoUiWebappBase", "loadAppInfoJson: allOfTheJsonText is null");
                    return null;
                } catch (Throwable th2) {
                    th = th2;
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e322) {
                            Trace.debug("NoUiWebappBase", "loadAppInfoJson: error closing stream", e322);
                        }
                    }
                    throw th;
                }
            } catch (Throwable th3) {
                th = th3;
                inputStream = inputStream2;
                if (inputStream != null) {
                    inputStream.close();
                }
                throw th;
            }
        } catch (Exception e5) {
            e22 = e5;
            Trace.debug("NoUiWebappBase", "loadAppInfoJson", e22);
            if (inputStream != null) {
                inputStream.close();
            }
            if (allOfTheJsonText == null) {
                return new JSONObject(allOfTheJsonText);
            }
            Trace.debug("NoUiWebappBase", "loadAppInfoJson: allOfTheJsonText is null");
            return null;
        }
        if (allOfTheJsonText == null) {
            return new JSONObject(allOfTheJsonText);
        }
        Trace.debug("NoUiWebappBase", "loadAppInfoJson: allOfTheJsonText is null");
        return null;
    }

    public String loadAppInfoJsonAsString() {
        try {
            return loadAppInfoJson().toString();
        } catch (Exception e) {
            Trace.debug("NoUiWebappBase", "loadAppInfoJsonAsString", e);
            return null;
        }
    }

    public long getWebappProcessId() {
        if (getPrivateWebAppSupportObject() != null) {
            return getPrivateWebAppSupportObject().getWebappProcessId();
        }
        return 0;
    }

    private NoUiWebappBase() {
    }

    protected NoUiWebappBase(Context backingContext) {
        this.mBackingContextRef = new WeakReference(backingContext);
        runDelayedConstruction();
    }

    public void runDelayedConstruction() {
        if (this.mPrivateWebAppSupportObject == null) {
            this.mPrivateWebAppSupportObject = WebappSupport.makeMeMyWebappSupportObject(this);
            this.mPrivateWebAppSupportObject.getPrivateJsKitAccess().signalWebappRunHostOnCreate();
        }
        if (getWebView() == null) {
            this.mPrivateWebAppSupportObject.onCreateOnOwner(null);
        }
        String queuedLoadUrl = getQueuedLoadUrlWithAtomicClear();
        if (queuedLoadUrl != null) {
            loadUrl(queuedLoadUrl);
        }
    }

    public void onBootstrapScriptLoadedAndReady(String extraDataFromJsLoading) {
        if (extraDataFromJsLoading == null) {
            Trace.debug("NoUiWebappBase", "onBootstrapScriptLoadedAndReady: extraDataFromJsLoading is null");
            return;
        }
        try {
            extraDataFromJsLoading = URLDecoder.decode(extraDataFromJsLoading, "UTF-8");
            try {
                final String urlSpec = new JSONObject(extraDataFromJsLoading).optString("loadUrl");
                if (!urlSpec.isEmpty()) {
                    SyncStepRunnable rn = null;
                    if (urlSpec.endsWith("js")) {
                        final String loadingParam = extraDataFromJsLoading;
                        rn = SyncStepRunnable.newRunnable(new Runnable() {
                            public void run() {
                                try {
                                    WebView webView = NoUiWebappBase.this.getWebView();
                                    if (webView != null) {
                                        webView.loadUrl("javascript:loadScript(\"" + urlSpec + "\")");
                                    }
                                } catch (Exception e) {
                                    String str = "%s::%s : [%s] ; failed to webView.loadUrl (in a Runnable)";
                                    Object[] objArr = new Object[3];
                                    objArr[0] = NoUiWebappBase.this.getClass().getSimpleName();
                                    objArr[1] = "onBootstrapScriptLoadedAndReady";
                                    objArr[2] = loadingParam == null ? "(null)" : loadingParam;
                                    PebbleWebappBaseActivity.LogSimpleError(str, objArr);
                                }
                            }
                        });
                    }
                    if (rn != null) {
                        if (JsKit.runOnAvailableActivityUiThread(this, rn)) {
                            rn.waitForRunToFinish(true);
                            Trace.debug("NoUiWebappBase", "wait end");
                        } else {
                            rn.run();
                        }
                    }
                }
                onResume();
            } catch (Exception e) {
                Trace.debug("NoUiWebappBase", "onBootstrapScriptLoadedAndReady", e);
            }
        } catch (Exception e2) {
            Trace.debug("NoUiWebappBase", "onBootstrapScriptLoadedAndReady", e2);
        }
    }

    public void loadUrl(String urlString) {
        String paramString = null;
        this.mLastUrlStringLoaded = urlString;
        try {
            JSONObject jo = new JSONObject();
            jo.put("loadUrl", urlString);
            paramString = jo.toString();
        } catch (Exception e) {
            Trace.debug("NoUiWebappBase", "loadUrl", e);
        }
        if (paramString != null) {
            try {
                paramString = "params=" + URLEncoder.encode(paramString, "UTF-8");
            } catch (UnsupportedEncodingException e2) {
                Trace.debug("NoUiWebappBase", "loadUrl", e2);
                paramString = null;
            }
        }
        if (paramString != null) {
            WebView webView = getWebView();
            if (webView != null) {
                webView.loadUrl("file:///android_asset/jskit_startup.html?" + paramString);
            } else {
                this.mQueuedLoadUrl = urlString;
            }
        }
    }

    public void loadUrlNoBootstrapScripts(String urlString) {
        if (urlString != null) {
            this.mLastUrlStringLoaded = urlString;
            WebView webView = getWebView();
            if (webView != null) {
                webView.loadUrl(urlString);
                return;
            }
            PebbleWebappBaseActivity.LogSimpleDebug("queueing loadUrl url = %s", urlString);
            this.mQueuedLoadUrl = urlString;
        }
    }

    public Context getBackingContext() {
        return (Context) this.mBackingContextRef.get();
    }

    public WebappSupport getPrivateWebAppSupportObject() {
        return this.mPrivateWebAppSupportObject;
    }

    public void flagForSubsequentTeardownOnDestroy() {
        if (this.mPrivateWebAppSupportObject != null) {
            this.mPrivateWebAppSupportObject.flagForSubsequentTeardownOnDestroy();
        }
    }

    public JsKitAccessor getPrivateJsKitAccess() {
        return this.mPrivateWebAppSupportObject.getPrivateJsKitAccess();
    }

    public void onCreate(Bundle savedInstanceState) {
        signalWebappRunHostOnCreate();
    }

    public void onDestroy() {
        boolean isFullTeardown = false;
        if (getPrivateWebAppSupportObject() != null) {
            isFullTeardown = getPrivateWebAppSupportObject().onDestroyOnOwner();
        }
        signalWebappRunHostOnDestroy(isFullTeardown);
        PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onDestroy");
    }

    public void onPause() {
        signalWebappRunHostOnPause();
    }

    public void onResume() {
        signalWebappRunHostOnResume();
    }

    public WebView getWebView() {
        return this.mPrivateWebAppSupportObject.getWebView();
    }

    public void signalWebappRunHostOnCreate() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnCreate();
        } else {
            Trace.debug("NoUiWebappBase", "signalWebappRunHostOnCreate: jskit is null");
        }
    }

    public void signalWebappRunHostOnDestroy(boolean isOnDestroyTheFullTeardown) {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnDestroy(isOnDestroyTheFullTeardown);
        } else {
            Trace.debug("NoUiWebappBase", "signalWebappRunHostOnDestroy: jskit is null");
        }
    }

    public void signalWebappRunHostOnPause() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnPause();
        } else {
            Trace.debug("NoUiWebappBase", "signalWebappRunHostOnPause: jskit is null");
        }
    }

    public void signalWebappRunHostOnResume() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnResume();
        } else {
            Trace.debug("NoUiWebappBase", "signalWebappRunHostOnResume: jskit is null");
        }
    }
}
